;
(function(window) {
	mui.plusReady(function() {
		batchRefresh("img");

		// img标签 加上preview-img-tap类选择器 即可单机实现预览功能
		bindPreviewImage("img.preview-img-tap");
	})
	// 设置单机预览图片
	function bindPreviewImage(el) {
		mui(document).on("tap", el, function() {
			const _src = this.getAttribute("src");
			var urls = [];
			urls.push(_src);
			previewImages(urls);
		})
	}

	window.previewImages = function(urls) {
		plus.nativeUI.previewImage(urls, {
			current: 0,
			loop: false,
			indicator: 'default'
		});
	}

})(window);

function initDocumentHeight() {
	var height = document.documentElement.clientHeight || document.body.clientHeight;
	plus.webview.currentWebview().setStyle({
		height: height,
	})
	window.resize = function() {
		plus.webview.currentWebview().setStyle({
			height: height,
		})
	}

}

function dateFormat(fmt, date) {
	let ret;
	const opt = {
		"Y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"H+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"S+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt;
}


// const _GLOBAL_SERVER_IP = "www.dmyily2.cn";
// const _GLOBAL_SERVER_IP = "10.0.1.85";
// const _GLOBAL_SERVER_IP = "192.168.43.15"; 
const _GLOBAL_SERVER_IP = "192.168.31.221";
const _GLOBAL_SERVER_HOST = "http://" + _GLOBAL_SERVER_IP + ":9700/rest";

const batchRefresh = function(tag) {
	mui(tag + "[data-flush]").each(function(i, imgObj) {
		refresh(imgObj);
		imgObj.addEventListener("tap", function() {
			refresh(this);
		})
	})
}

function refresh(imgObj) {
	var targetUrl = imgObj.getAttribute("src").replace("\$\{server.host\}", _GLOBAL_SERVER_HOST);
	var _t = targetUrl.split("?");
	targetUrl = _t[0] + "?_t=" + new Date().getTime()
	console.log(targetUrl)
	imgObj.setAttribute("src", targetUrl)
	imgObj.style.display = "inline-block";
}
const _request = function(url, type, data, headers) {
	if (!headers) {
		headers = {};
	}
	if (!type) {
		type = "get";
	}
	return new Promise(function(resolve, reject) {
		mui.ajax(url, {
			data: data,
			dataType: 'json', //服务器返回json格式数据
			type: type,
			timeout: 10000, //超时时间设置为10秒；
			contentType: ((type === "get") ? 'application/x-www-form-urlencoded;charset=UTF-8' :
				'application/json;charset=utf-8'),
			headers: headers,
			success: function(data) {
				//服务器返回响应，根据响应结果，分析是否登录成功；
				resolve(data);
			},
			error: function(xhr, type, errorThrown) {
				reject(xhr);
			}
		});
	})

}
const _SERVER = {
	user: {
		login(_data) {
			return _request(_GLOBAL_SERVER_HOST + "/user/login", "post", _data);
		},
		regist(_data) {
			return _request(_GLOBAL_SERVER_HOST + "/user/regist", "post", _data);
		},
		updatePhoto(userId, imgAddr) {
			return _request(_GLOBAL_SERVER_HOST + "/user/updatePhoto", "post", {
				id: userId,
				photoDefault: imgAddr
			});
		},
		getQrCode(token) {
			return _request(_GLOBAL_SERVER_HOST + "/user/loadQR/" + token, "get");
		},
		findUser(userId) {
			return _request(_GLOBAL_SERVER_HOST + "/user/find/" + userId, "get");
		},
		addFriendsRequest(userId, type, token) {
			return _request(_GLOBAL_SERVER_HOST + "/user/add_request/" + token, "post", {
				userId: userId,
				r_type: type
			});
		},
		getUserInfo(token) {
			return _request(_GLOBAL_SERVER_HOST + "/user/getUserInfo/" + token, "get");
		},
		queryUserByUserName(uname) {
			return _request(_GLOBAL_SERVER_HOST + "/user/queryUser/" + uname, "get");
		},
		queryFriendsRequest(token) {
			return _request(_GLOBAL_SERVER_HOST + "/user/queryFriendsRequest/" + token, "get");
		},
		acceptUserReq(token, reqId) {
			return _request(_GLOBAL_SERVER_HOST + "/user/acceptReq/" + token, "post", {
				reqId: reqId
			});
		},
		ignoreUserReq(token, reqId) {
			return _request(_GLOBAL_SERVER_HOST + "/user/ignore/" + token, "post", {
				reqId: reqId
			});
		},
		getFriends(token) {
			return _request(_GLOBAL_SERVER_HOST + "/user/friends/" + token, "get");
		}
	},
	// 图灵机器人
	robat: {
		// 聊天
		chat(content) {
			return _request("http://www.tuling123.com/openapi/api?key=acfbca724ea1b5db96d2eef88ce677dc&info=" + content, "get");
		}
	}
}

const Coder = {
	Encoder: function(content, cmd, send, rec) {
		this.content = content;
		this.cmd = cmd;
		this.send = send;
		this.rec = rec;
		this.encode = function() {
			return {
				"cmd": this.cmd,
				"content": this.content,
				"send": this.send,
				"rec": this.rec
			};
		}
		this.encodeAsString = function() {
			return JSON.stringify(this.encode());
		}
	}
}

// 对websocket的封装
const Socket = function(url) {
	this.url = url;

	this.websocket;

	this.onmessage;
	this.onopen;
	this.onclose;

	this.send = function(content) {

		if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
			this.init();
			setTimeout(() => {
				this.websocket.send(JSON.stringify(content));
			}, 1000)
			return;
		}

		this.websocket.send(JSON.stringify(content));
	}

	this.init = function() {
		this.websocket = new WebSocket(this.url);

		this.websocket.onerror = this.onerror;
		this.websocket.onmessage = this.onmessage;
		this.websocket.onclose = this.onclose;
		this.websocket.onopen = this.onopen;
	}
}
Socket.prototype.onerror = function(e) {
	console.log(JSON.stringify(e))
}


const _EventType = {
	LOGIN: 10,
	CHAT_SEND: 20,
	CHAT_FRIEND: 21,
	FRIENDS_FLUSH: 31
}

const APP = {
	cache: {
		UserFriends: {
			set(userId, obj) {
				var friendsKey = "chat-friend-" + userId;
				var friendsList = [];
				for (var key in obj) {
					var list = obj[key];
					for (var i = 0; i < list.length; i++) {
						friendsList.push(list[i]);
					}
				}
				plus.storage.setItem(friendsKey, JSON.stringify(friendsList));
			},
			get(userId) {
				var friendsKey = "chat-friend-" + userId;
				var friendList = plus.storage.getItem(friendsKey);
				return JSON.parse(friendList)
			}
		}

	},
	model: {
		Message: function(friendId, friendPhoto, friendName, msgText, isRead) {
			this.friendId = friendId;
			this.friendPhoto = friendPhoto;
			this.friendName = friendName;
			this.msgText = msgText;
			this.isRead = isRead;
		},
		MessageManager: function(userId) {
			this.cacheKet = "chat-user-msg-list-" + userId;
			this.pushMsg = function(message) {
				if (message.constructor.name !== 'Message') {
					console.error("message is not a Message Type");
					return;
				}
				var msgs = [];
				var msgsAsString = plus.storage.getItem(this.cacheKet);
				if (msgsAsString && msgsAsString !== '') {
					msgs = JSON.parse(msgsAsString);
				}

				msgs.unshift(message);
				for (var i = 1; i < msgs.length; i++) {
					if (msgs[i].friendId === message.friendId) {
						msgs.splice(i, 1);
						break;
					}
				}
				plus.storage.setItem(this.cacheKet, JSON.stringify(msgs));
			}

			this.getMsg = function() {
				return JSON.parse(plus.storage.getItem(this.cacheKet));
			}

			this.eliminateAngle = function(friendId, callbackFn) {

				const _msgs = this.getMsg();

				for (var i = 0; i < _msgs.length; i++) {
					if (_msgs[i].friendId === friendId) {
						_msgs[i].isRead = true;
					}
				}

				plus.storage.setItem(this.cacheKet, JSON.stringify(_msgs));

				if (callbackFn) {
					callbackFn();
				}
			}
		},

		MsgHistoryManager: function(userId, friendId) {
			this.key = "chat-history-" + userId + "-" + friendId;
			this.pushMsg = function(msgHistory) {
				var history = [];
				var hisAsString = plus.storage.getItem(this.key);
				if (hisAsString) {
					history = JSON.parse(hisAsString);
				}
				history.push(msgHistory);
				plus.storage.setItem(this.key, JSON.stringify(history));
			}
			this.getMsg = function() {
				var history = null;
				var hisAsString = plus.storage.getItem(this.key);
				if (hisAsString) {
					history = JSON.parse(hisAsString);
				}
				return history;
			}
		}
	}

}
